LocalSceneHandler = LocalServerBaseHandler.New()

local t = LocalSceneHandler

function t:Register()
    self:RegisterReq(150222) --玩家发起PK
    self:RegisterReq(150221) --通知服务端,场景loading完毕
    self:RegisterReq(150202) --主角自己状态同步移动消息
    self:RegisterReq(150224) --采矿
    self:RegisterReq(151202) --请求进入暗巷
    self:RegisterReq(151203)--暗巷信息
    self:RegisterReq(151205)--请求攻击暗巷宝石

    self.autoFightData = {time = 0,maxTime = 1}
end
function t:Update(dt)
    self.battleTime = self.battleTime + dt
    --[[if self.battleTime > 10 then
        local m = ResDarkResultMessage.New()--结算
        m.money = 1000
        LocalServer.Send(m)
        self:UnRegisterUpdate()
        return
    end]]
    --auto fight me
    self.autoFightData.time = self.autoFightData.time + dt
    if self.autoFightData.time < self.autoFightData.maxTime then
        return
    end
    self.autoFightData.time = 0
    local inBat = RedRob.ClientBattle.IsInBattle()
    if not inBat then return end
    local main = RedRob.ActorManager.GetActor(RedRob.KeyController.GetCtrlId())--logicMgr.HeroManager.GetRoleId())
    if not main then return end
    local _list = RedRob.ActorManager.GetActorList()
    for k,v in pairs(_list) do
        if v:IsType(RedRob.Config.ActorType.player) and v~= main and v:CanAttack() then
            local target = self:GetRandomPlayer(v)
            if target then
                v.ai:PursuitTarget(target,2,function()
                    if v:CanAttack() and target:CanAttack() then
                        local p = v:GetPos()
                        RedRob.BattleMsgHandler.ReqPkByAi(v:GetId(),target:GetId(),p.x,p.y)
                    end
                end)
            end
        end
    end
end
---@param expectActor RedRob.Pawn
---@return RedRob.Player
function t:GetRandomPlayer(expectActor)
    local mList = {}
    local _list = RedRob.ActorManager.GetActorList()
    for k,v in pairs(_list) do
        if v:IsType(RedRob.Config.ActorType.player) and v ~= expectActor and not v:IsInBattle() and not v:IsDead() then
            table.insert(mList,v)
        end
    end
    if #mList == 0 then return nil end
    local r = math.random(1,#mList)
    return mList[r]
end
function t:Receive(msg)
    if msg.msgId == 151203 then--暗巷信息
        local res = ResDarkAlleyInfoMessage.New()
        res.status = 1
        res.joinNum = 0
        res.gotMoney = 0
        res.nextTime = (HelperFunc.GetServerTime()+30*60)*1000
        LocalServer.Send(res)
    elseif msg.msgId == 150222 then --玩家发起PK
        local res = ResPkInfoMessage.New()
        local info = PkInfo.New()
        res.pkInfo = info

        info.startTime = RedRob.ClientBattle.GetBattleTime()*1000--HelperFunc.GetServerTime(false)
        local mainId = RedRob.KeyController.GetCtrl():GetId()
        if msg.attackId then
            info.playerId1 = msg.attackId
        else
            info.playerId1 = mainId
        end
        info.playerId2 = msg.playerId
        local winId = math.random(1,100) > 50 and info.playerId1 or info.playerId2
        if mainId == info.playerId1 or mainId == info.playerId2 then
            winId = mainId
        end
        info.playerIdWin = winId
        local failedId = winId == info.playerId1 and info.playerId2 or info.playerId1
        local x1,y1,x2,y2 = self:GetAttackPos(info.playerId1,info.playerId2)
        info.x1 = x1
        info.y1 = y1
        info.x2 = x2
        info.y2 = y2
        info.winStreak1 = math.random(0,6)
        info.winStreak2 = math.random(0,6)
        info.moneyChange = 10
        info.remainHp = math.random(1,70)
        res.attrReduce = math.random(1,100) > 50 and 10 or 0
        info.time = 5
        LocalServer.Send(res)
        utimer.timeCall(function()
            self:Reborn(failedId)
        end,10000)
        utimer.timeCall(function()
            self:SendBuffMsg(winId,210001400)
        end,5000)
    elseif msg.msgId == 150221 then --通知服务端,场景loading完毕

        local res = ResSceneObjMessage.New()
        res.onSeePlayers = {}
        res.removeObjs = {}
        res.onSeeMinerals = {}
        res.onSeeDarkStones = {}
        local pic = HeroManager.GetRoleInfo("pic")
        local player = self:CreatePlayerObj(HeroManager.GetRoleId(),pic,"主角")
        table.insert(res.onSeePlayers,player)

        local heroList = {}
        local cfg = dataTable.getDataTable("t_Hero")
        for k,v in pairs(cfg) do
            if v.f_Type == 0 then
                table.insert(heroList,pic)
            end
        end
        local start = 11
        local count = 1
        local _end = math.min(start+count-1,#heroList)
        for i = start,_end do  --玩家
            local player = self:CreatePlayerObj(RedRob.ActorManager.GetUniqueId(),heroList[i],"机器人"..i)
            player.buffList = {{buffId = 210001400,overlay = 1}}
            table.insert(res.onSeePlayers,player)
        end
        for i = 2,5 do  --宝箱
            local m = MineralObj.New()
            m.x = math.random(1.01,4.01)
            m.y = math.random(1.01,4.01)
            m.objId = RedRob.ActorManager.GetUniqueId()
            m.modelId = i
            m.status = 0
            table.insert(res.onSeeMinerals,m)
        end
        local stoneCfg = dataTable.getDataTable("t_darkstreetstone")
        for k,v in pairs(stoneCfg) do
            local s = DarkStoneObj.New()
            s.x = v.f_StonePos[1]
            s.y = v.f_StonePos[2]
            s.objId = RedRob.ActorManager.GetUniqueId()
            s.modelId = v.f_Id
            s.status = 0
            s.hp = v.f_StoneLife
            s.maxHp = v.f_StoneLife
            table.insert(res.onSeeDarkStones,s)
        end
        LocalServer.Send(res)
        self:RegisterUpdate()
    elseif msg.msgId == 150202 then --主角自己状态同步移动消息
        local playerId = msg.playerId
        if not playerId then
            playerId = RedRob.KeyController.GetCtrl():GetId()
        end
        local res = ResMoveMessage.New()
        res.playerId = playerId
        res.currX = msg.currX
        res.currY = msg.currY
        res.x = msg.x
        res.y = msg.y
        LocalServer.Send(res)
    elseif msg.msgId == 151202 then--请求进入暗巷
        local res = ResSceneInfoMessage.New()
        res.sceneId = 1
        res.x = 3
        res.y = 3
        res.direction = 1
        LocalServer.Send(res)
    elseif msg.msgId == 150224 then--请求采矿
        local res = ResMineralChangeMessage.New()
        res.objId = msg.objId
        res.status = 1
        res.playerId = RedRob.KeyController.GetCtrlId()--logicMgr.HeroManager.GetRoleId()
        LocalServer.Send(res)
        ---@type RedRob.Minerals
        local mineral = RedRob.ActorManager.GetActor(msg.objId)
        local modelId = mineral:GetModelId()
        local cfg = dataTable.getDataTableByStringId("t_mineral",modelId)
        if cfg.f_buffs ~= "" then
            local res2 = ResBuffMessage.New()
            res2.objId = RedRob.KeyController.GetCtrlId()--logicMgr.HeroManager.GetRoleId()
            res2.actionType = 1
            res2.buffInfo = BuffInfo.New()
            res2.buffInfo.buffId = cfg.f_buffs[1]
            res2.buffInfo.overlay = math.random(1,10)
            LocalServer.Send(res2)
        end
        utimer.delayCall(function()
            local res3 = ResSceneObjMessage.New()
            res3.onSeePlayers = {}
            res3.removeObjs = {}
            res3.onSeeMinerals = {}
            table.insert(res3.removeObjs,msg.objId)
            LocalServer.Send(res3)
        end,2000)
        utimer.delayCall(function()
            local res3 = ResSceneObjMessage.New()
            res3.onSeePlayers = {}
            res3.removeObjs = {}
            res3.onSeeMinerals = {}
            local m = MineralObj.New()
            m.x = math.random(1.01,4.01)
            m.y = math.random(1.01,4.01)
            m.objId = RedRob.ActorManager.GetUniqueId()
            m.modelId = modelId
            m.status = 0
            table.insert(res3.onSeeMinerals,m)
            LocalServer.Send(res3)
        end,3000)
    elseif msg.msgId == 151205 then
        local res = ResAtkStoneMessage.New()
        res.objId = msg.objId
        res.playerId = RedRob.KeyController.GetCtrlId()
        res.damage = 1
        local actor = RedRob.ActorManager.GetActor(msg.objId)
        res.currHp = math.max(0,actor.hp-1)
        LocalServer.Send(res)
    end

end
function t:GetAttackPos(attackId,defenderId)
    local attack = RedRob.ActorManager.GetActor(attackId)
    local target = RedRob.ActorManager.GetActor(defenderId)
    local p = target:GetPos()
    local s = attack:GetPos()
    local targetPos =  Vector3.New()
    local radius = attack:GetAttackRadius()
    local offset = 0.01 --攻击半径往里走点，否则刚好在半径上，CheckAttackPos检测就有问题
    local centerV = Vector3.New()
    centerV:SetV(p):Add(s):Div(2) --中心点
        targetPos:Set(centerV.x - radius+offset,centerV.y,centerV.z)
    local x1 = targetPos.x
    local y1 = targetPos.y
    targetPos:Set(centerV.x + radius-offset,centerV.y,centerV.z)
    local x2 = targetPos.x
    local y2 = targetPos.y
    if Vector3.Distance(s,Vector3(x1,y1)) < Vector3.Distance(s,Vector3(x2,y2)) then
        return x1,y1,x2,y2
    else
        return x2,y2,x1,y1
    end

end
function t:CreatePlayerObj(id,pic,name)
    local obj = PlayerObj.New()
    local bat = RedRob.ClientBattle
    local x,y = bat.GetLimitRandomPos()
    obj.x = x--math.random(5.01,6.01)
    obj.y = y--math.random(4.01,5.01)
    obj.playerId = id
    obj.name = name
    obj.pic = pic
    obj.unionName = ""
    obj.picFrame = 0
    obj.onMove = 0
    obj.destX = 0
    obj.destY = 0
    obj.direction = math.random(1,100) > 50 and 1 or 0
    obj.die = 0
    obj.attrReduce = 0
    obj.currMoney = 100
    obj.buffList = {}
    return obj
end
function t:Reborn(playerId)
    --self:SendRemovePlayerMsg()
    --if playerId == logicMgr.HeroManager.GetRoleId() then
        local res = ResRelifeMessage.New()
        res.playerId = playerId
        local x,y = RedRob.ClientBattle.GetLimitRandomPos()
        res.x = x--math.random(5.01,6.01)
        res.y = y--math.random(4.01,5.01)
        LocalServer.Send(res)
    --end

end
function t:SendBuffMsg(playerId,buffId)
    local res = ResBuffMessage.New()
    res.objId = playerId
    res.buffInfo = BuffInfo.New()
    res.buffInfo.buffId = buffId
    res.buffInfo.overlay = 1
    res.actionType = 1
    LocalServer.Send(res)
end
function t:SendCreatePlayerMsg(model)
    local res = ResSceneObjMessage.New()
    res.onSeePlayers = {}
    res.removeObjs = {}
    res.onSeeMinerals = {}
    --local model = math.random(1,50)
    local player = self:CreatePlayerObj(RedRob.ActorManager.GetUniqueId(),model,"机器人")
    player.buffList = {}
    table.insert(res.onSeePlayers,player)
    LocalServer.Send(res)
end
function t:SendRemovePlayerMsg()
    local res = ResSceneObjMessage.New()
    res.onSeePlayers = {}
    res.removeObjs = {}
    res.onSeeMinerals = {}
    local main = RedRob.ActorManager.GetActor(RedRob.KeyController.GetCtrlId())--logicMgr.HeroManager.GetRoleId())
    if not main then return end
    local _list = RedRob.ActorManager.GetActorList()
    local _removeModels = {}
    for k,v in pairs(_list) do
        if v:IsType(RedRob.Config.ActorType.player) and v~= main and v:IsDead() then
            table.insert(res.removeObjs,v:GetId())
            table.insert(_removeModels,v:GetModelId())
        end
    end
    LocalServer.Send(res)
    for k,v in pairs(_removeModels) do
        self:SendCreatePlayerMsg(v)
    end
end